﻿Imports Odyssee.WebControles

Public MustInherit Class FichePage(Of TCleEntite,
                                      TEntite As {Class, New},
                                      TWCFClient As {IDisposable, Class, New},
                                      TCriteresRecherche As Class)
    Inherits OpenDelibPage

    Public Property ModeFiche As Tools.ModeFiche
        Get
            Return CType(ViewState("mode_fiche"), Tools.ModeFiche)
        End Get
        Private Set(value As Tools.ModeFiche)
            ViewState("mode_fiche") = value
        End Set
    End Property
    Public Property CleEntite As TCleEntite
        Get
            Return CType(ViewState("cle_entite"), TCleEntite)
        End Get
        Protected Set(value As TCleEntite)
            ViewState("cle_entite") = value
        End Set
    End Property
    Public Property Entite As TEntite
        Get
            Return CType(ViewState("entite"), TEntite)
        End Get
        Private Set(value As TEntite)
            ViewState("entite") = value
        End Set
    End Property

    Public MustOverride ReadOnly Property Titre As String
    Protected MustOverride ReadOnly Property LibelleEntite As String
    Protected MustOverride ReadOnly Property LibelleFeminin As Boolean
    Protected MustOverride ReadOnly Property LibelleApostrophe As Boolean
    Protected MustOverride ReadOnly Property PopupPanel As JQPopupPanel
    Protected MustOverride ReadOnly Property BoutonActualiser As Button
    Protected MustOverride ReadOnly Property SeparateurActualiser As ToolBarSeparator
    Protected MustOverride ReadOnly Property BoutonEnregistrer As Button


    Protected Overrides Sub OnInit(e As EventArgs)
        MyBase.OnInit(e)

        Dim appPath As String = Request.ApplicationPath
        If appPath = "/" Then
            appPath = ""
        End If

        AddCss(Page, appPath & "/Css/Fiche.css")
    End Sub

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Master.Titre = Me.Titre

        RemoveHandler Me.BoutonActualiser.Click, AddressOf btnActualiser_Click
        AddHandler Me.BoutonActualiser.Click, AddressOf btnActualiser_Click
        RemoveHandler Me.BoutonEnregistrer.Click, AddressOf btnEnregister_Click
        AddHandler Me.BoutonEnregistrer.Click, AddressOf btnEnregister_Click

        If Not IsPostBack Then
            ' Lecture des paramètres
            Me.ModeFiche = CType(Request.QueryString("modeFiche"), Tools.ModeFiche)
            Me.CleEntite = Nothing

            ' Chargement de l'entité depuis le service web
            InitialiserEntite()

            ' Chargement des paramètres
            InitialiserParametres()

            ' Chargement de la page
            InitialiserPage()
        End If
    End Sub


    Private Sub btnActualiser_Click(sender As Object, e As EventArgs)
        InitialiserEntite()
        InitialiserPage()
    End Sub

    Private Sub btnEnregister_Click(sender As Object, e As EventArgs)
        Enregistrer()
    End Sub


    Protected Sub InitialiserEntite()
        If ModeFiche = Tools.ModeFiche.Modification Then
            Dim cle As String = Server.UrlDecode(Request.QueryString("cle"))

            If String.IsNullOrEmpty(cle) OrElse
              (IsNumeric(cle) AndAlso CInt(cle) <= 0) Then
                Me.ModeFiche = Tools.ModeFiche.Creation
            Else
                Me.CleEntite = CType(Convert.ChangeType(cle, GetType(TCleEntite)), TCleEntite)

                Using svc As New TWCFClient
                    Dim criteres As TCriteresRecherche = InitialiserCriteresRechercheEntite(Me.CleEntite)
                    If criteres Is Nothing Then
                        Me.ModeFiche = Tools.ModeFiche.Creation
                        Me.CleEntite = Nothing
                    Else

                        Try
                            Dim ok As Boolean = False
                            Dim msgErreur As String = ""
                            Dim liste As List(Of TEntite) = RechercherEntite(svc, criteres, ok, msgErreur)

                            If liste IsNot Nothing AndAlso ok Then
                                If liste.Count <= 0 Then
                                    NotifyErreur("L" & If(Me.LibelleApostrophe, "'", If(Me.LibelleFeminin, "a ", "e ")) & Me.LibelleEntite & " ayant pour clé '" & CleEntite.ToString & "' est introuvable !")
                                    Me.ModeFiche = Tools.ModeFiche.Creation
                                    Me.CleEntite = Nothing
                                Else
                                    Me.Entite = liste(0)
                                End If
                            Else
                                NotifyErreur(msgErreur)
                                Me.ModeFiche = Tools.ModeFiche.Creation
                                Me.CleEntite = Nothing
                            End If


                        Catch ex As Exception
                            NotifyErreur(ex.Message)
                            Me.ModeFiche = Tools.ModeFiche.Creation
                            Me.CleEntite = Nothing
                        End Try

                    End If
                End Using
            End If
        End If

        If Me.ModeFiche = Tools.ModeFiche.Creation Then
            Me.Entite = New TEntite()
        End If

        InitialiserObjetEntite(Me.Entite)
    End Sub

    Protected MustOverride Function InitialiserCriteresRechercheEntite(cle As TCleEntite) As TCriteresRecherche
    Protected MustOverride Function RechercherEntite(svc As TWCFClient, criteres As TCriteresRecherche, ByRef ok As Boolean, ByRef messageErreur As String) As List(Of TEntite)
    Protected MustOverride Sub InitialiserObjetEntite(entite As TEntite)

    Protected Overridable Sub InitialiserParametres()
    End Sub

    Protected Overridable Sub InitialiserPage()
        Select Case Me.ModeFiche

            Case Tools.ModeFiche.Creation
                Me.BoutonActualiser.Visible = False
                Me.SeparateurActualiser.Visible = False

            Case Tools.ModeFiche.Modification


        End Select
    End Sub

    Protected Sub InitialiserDescripteurs(thesaurus As String, gv As GridView, libelle As String)
        Using svc As New ServiceDescripteurs.DescripteursClient
            Dim params As New ServiceDescripteurs.ParametresListeDescripteursLies
            params.Authentication = New ServiceDescripteurs.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Cle = Me.CleEntite
            params.Thesaurus = thesaurus
            params.TypeEntite = 1

            Dim results As ServiceDescripteurs.ResultatRechercheDescripteurs = Nothing
            Try
                results = svc.ListeDescripteursLies(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger les " & libelle & " d" & If(Me.LibelleApostrophe, "e l'", If(Me.LibelleFeminin, "e la ", "u ")) & Me.LibelleEntite & " '" & Me.CleEntite.ToString & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    gv.DataSource = results.Descripteurs
                    gv.DataBind()
                    CType(gv.HeaderRow.Cells(gv.Columns.Count - 1).Controls(1), JQPopupButton).URLParameters = "&thesaurus=" + thesaurus
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub AjouterDescripteur(thesaurus As String, descripteur As String, gv As GridView, libelle As String)
        Using svc As New ServiceDescripteurs.DescripteursClient
            Dim params As New ServiceDescripteurs.ParametresLienDescripteur
            params.Authentication = New ServiceDescripteurs.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Cle = CleEntite
            params.Descripteur = descripteur
            params.Thesaurus = thesaurus
            params.TypeEntite = 1

            Try
                Dim results As ServiceDescripteurs.OperationResult
                results = svc.AjouterLienDescripteur(params)
                If results.OK Then
                    NotifySuccess("Ajout effectué avec succès.")
                    InitialiserDescripteurs(thesaurus, gv, libelle)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerDescripteur(thesaurus As String, descripteur As String, gv As GridView, libelle As String)
        Using svc As New ServiceDescripteurs.DescripteursClient
            Dim params As New ServiceDescripteurs.ParametresLienDescripteur
            params.Authentication = New ServiceDescripteurs.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Cle = CleEntite
            params.Descripteur = descripteur
            params.Thesaurus = thesaurus
            params.TypeEntite = 1

            Try
                Dim results As ServiceDescripteurs.OperationResult
                results = svc.SupprimerLienDescripteur(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserDescripteurs(thesaurus, gv, libelle)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub

    Private Sub Enregistrer()
        If Not Renseigner() Then Return

        If Me.ModeFiche = Tools.ModeFiche.Creation Then
            If Not Creer() Then Return
            ' Rechargement complet de la page
            Response.Redirect(Request.Url.GetLeftPart(UriPartial.Path) & "?modeFiche=1&cle=" & Me.CleEntite.ToString)

        ElseIf Me.ModeFiche = Tools.ModeFiche.Modification Then
            ' Mise à jour
            If Not MettreAJour() Then Return

        End If
    End Sub

    Protected MustOverride Function Renseigner() As Boolean
    Protected MustOverride Function Creer() As Boolean
    Protected MustOverride Function MettreAJour() As Boolean
End Class
